<?php
/**
 * Created by JetBrains PhpStorm.
 * User: shaoshuai
 * Date: 12-7-15
 * Time: 下午9:05
 */
class User
{
    /**
     * @var string
     */
    protected $name;

    /**
     * @var string
     */
    protected $eventFile;

    /**
     * @var string
     */
    protected $dataFile;

    public function __construct($config)
    {
        $this->name = $config['name'];
        $this->eventFile = $this->name . '.event';
        $this->dataFile = $this->name . '.data';
        $this->initEvent();
    }

    private function initEvent()
    {
        if (!file_exists($this->eventFile)) {
            file_put_contents($this->eventFile, '[]');
        }
    }

    private function initData()
    {
        if (!file_exists($this->dataFile)) {
            file_put_contents($this->dataFile, '{}');
        }
    }

    /**
     * 如果有新事件返回事件数组的json，如果没有新事件返回空字符串
     * @return string
     */
    public function checkNewEvent()
    {
        $fileContent = file_get_contents($this->eventFile);
        if ($fileContent == '[]') {
            $fileContent = '';
        } else {
            file_put_contents($this->eventFile, '[]');
        }
        return $fileContent;
    }

    /**
     * @param Event $event
     */
    public function receiveEvent(Event $event)
    {
        $events = json_decode(file_get_contents($this->eventFile), true);
        array_push($events, $event->getData());
        file_put_contents($this->eventFile, json_encode($events));
    }

    /**
     * @param string $key
     * @param mixed $value
     */
    public function setData($key, $value)
    {
        $data = json_decode(file_get_contents($this->dataFile), true);
        $data[$key] = $value;
        file_put_contents($this->dataFile, json_encode($data));
    }

    /**
     * @param string $key
     * @return mixed
     */
    public function getData($key)
    {
        $data = json_decode(file_get_contents($this->dataFile), true);
        return $data[$key];
    }

    /**
     * @param string $username
     */
    public function setName($username)
    {
        $this->name = $username;
    }

    /**
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }
}
